<template>

  <div class="app-container">

    <h2 style="text-align: center;">发布新课程</h2>

    <el-steps :active="1" process-status="wait" align-center style="margin-bottom: 40px;">
      <el-step title="填写课程基本信息"/>
      <el-step title="创建课程大纲"/>
      <el-step title="提交审核"/>
    </el-steps>

  
    <el-form label-width="120px">

    <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
    </el-form-item>

    <!-- 所属分类 TODO -->
    <!-- 一级分类 -->
    <el-form-item label="课程类别">
      <el-select
        v-model="courseInfo.subjectParentId"
        @change="loadTwoSubject"
        placeholder="请选择">
        <el-option
          v-for="subject in subjectNestedList"
          :key="subject.id"
          :label="subject.title"
          :value="subject.id"/>
      </el-select>
      <!-- 二级分类 -->
      <el-select v-model="courseInfo.subjectId" placeholder="请选择">
        <el-option
          v-for="subject in subSubjectList"
          :key="subject.value"
          :label="subject.title"
          :value="subject.id"/>
      </el-select>
    </el-form-item>
    <!-- 课程讲师 -->
    <el-form-item label="课程讲师">
      <el-select
        v-model="courseInfo.teacherId"
        
        placeholder="请选择">
        <el-option
          v-for="teacher in teacherList"
          :key="teacher.id"
          :label="teacher.name"
          :value="teacher.id"/>
      </el-select>
    </el-form-item>
    <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
    </el-form-item>

   <!-- 课程简介-->
    <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description"/>
    </el-form-item>

    <!-- 课程封面 TODO -->
    <!-- 课程封面-->
    <el-form-item label="课程封面">

      <el-upload
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload"
        :action="BASE_API+'/admin/oss/file/upload?host=cover'"
        class="avatar-uploader">
        <img :src="courseInfo.cover">
      </el-upload>

    </el-form-item>

    <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
    </el-form-item>

    <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="next">保存并下一步</el-button>
    </el-form-item>
</el-form>

  </div>
  
</template>
<script>
import course from '@/api/course'
import subject from '@/api/subject'
import teacher from '@/api/teacher'
import Tinymce from '@/components/Tinymce'
const defaultForm = {
  title: '',
  subjectId: '',
  subjectParantId:'',
  teacherId: '',
  lessonNum: 0,
  description: '',
  price: 0,
  cover: '/static/1.jpg' //设置课程封面默认图片
}

export default { 
  components: { Tinymce },
  data() {
    return {

      BASE_API: process.env.BASE_API, // 接口API地址
      OSS_PATH: process.env.OSS_PATH, // 阿里云OSS地址
      courseInfo: defaultForm,
      saveBtnDisabled: false ,// 保存按钮是否禁用
      subjectNestedList: [],//一级分类列表
      subSubjectList: [],//二级分类列表
      teacherList:[]//所有的讲师列表
    
    }
  },
  created() {
    console.log('info created')
    this.init()
  },
  methods: {
    
    init(){
       
        if(this.$route.params && this.$route.params.id){
            //如果没有id就是数据回显
            const id = this.$route.params.id ;
            this.fetchCourseInfo(id)
        }else{
            //判断路由中有没有id值   
            //将内容设置为空 
            this.courseInfo = {...defaultForm}
              //加载一级分类
            this.loadOneSubject()
            //加载所有讲师
            this.loadTeacherList()
        }
       
     
    },
    fetchCourseInfo(id){
       course.getCourseInfoById(id).then(response =>{
        this.courseInfo =  response.data.courseInfo 
        //把一级分类和二级分类数据回显示 
        //获取所有的分类信息
        subject.getSubjectList().then(response=>{
            this.subjectNestedList = response.data.items 
            for(let i = 0;i < this.subjectNestedList.length;i++){
               let oneSubject = this.subjectNestedList[i] 
                //判断当前一级分类id和数据库里面的id是否相同 
                if(oneSubject.id  == this.courseInfo.subjectParentId){
                   this.subSubjectList = oneSubject.children 
                   
                }
            }
        })
       })
       this.loadTeacherList()
    },
    //加载所有讲师的方法
    loadTeacherList(){
          teacher.getListAll().then(response=>{
            this.teacherList = response.data.list
          })
    },
    //加载二级分类的方法 
    loadTwoSubject(value){
      //根据一级分类查二级分类 
      //把value一级分类对应的二级分类，显示到下拉列表 
      for(let i = 0;i < this.subjectNestedList.length ;i++){
          //把每个对象获取到
          let subjectObject = this.subjectNestedList[i] 
          //=== 比较类型 也比较值  
          //==  比较值
          if(subjectObject.id === value){
              this.subSubjectList = subjectObject.children
              this.courseInfo.subject = ''
          }
      }
    },
    //记载一级分类的方法
    loadOneSubject(){
        subject.getSubjectList()
          .then(response=>{
            //把一级分类获取复制给subject
            console.log(response.data)
            this.subjectNestedList = response.data.items
            
          })
    },
    next() {
      console.log('next')
      //判断做添加操作还是修改操作 
      if(!this.courseInfo.id){
        this.saveCourseInfo()
      }else{
        //更新数据
          this.updateData()
           // this.$router.push({ path: '/edu/course/chapter/1' })
      }
    },
    saveCourseInfo(){
        course.saveCourseInfo(this.courseInfo).then(response =>{
            this.$message({
                type: 'success',
                message: '保存成功!'
            })
            return response  
        }).then(response =>{
            //路由跳转 
            this.$router.push({path: `/edu/course/chapter/${response.data.courseId}`})
        }).catch(response =>{
            this.$message({
                type: 'error',
                message: '添加课程信息失败'
            })
        })
    },
    handleAvatarSuccess(res, file) {
       //显示上传之后的图片 
       this.courseInfo.cover =  res.data.url 
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    updateData(){
        course.updateCourseId(this.courseInfo).then(response=>{
               this.$message({
                type: 'success',
                message: '修改成功!'
                
            }) 
            return response 
        }).then(response=>{
            this.$router.push({ path: '/edu/course/chapter/' + this.courseInfo.id })
        }).catch(response=>{
            this.$message({
                type: 'error',
                message: '修改失败'
            })
        })
    }
  }
}
</script>
<style scoped>
  .tinymce-container {
    line-height: 29px;
  }
</style>